//1.创建路由对象
var express = require('express');
var router = express.Router();
const furModel = require('../models/furModel');
//2.挂载对象
//批量转存接口
router.post('/fanji',async(req, res) =>{
    let arr=req.body.list
    
    try {
      let result=await furModel.insertMany(arr)
      console.log('删除结果',result);
      res.send({
        code:1,
        msg:'家具录入数据成功',
      });
    } catch (error) {
      res.send({
        code:0,
        msg:'家具录入失败',
        error,
      });
    }
  })

  router.delete('/fanji', async(req, res) =>{
    let {id}=req.query;//条件
    try {
        let result = await furModel.deleteOne({_id:id});
        console.log('删除结果',result);
        res.send({
            code:1,
            msg:'删除数据成功',
          });
    } catch (error) {
        res.send({
            code:0,
            msg:'删除数据失败',
            error,
          });
    }
   
  })

  router.put('/fanji', async(req, res) =>{
   let {id}=req.query;//条件
   try {
    await furModel.updateOne({_id:id},req.body);
    res.send({
        code:1,
        msg:'更新数据成功',
      });
   } catch (error) {
    res.send({
        code:0,
        msg:'更新数据失败',
        error,
        }); 
        } 
  })
  //更新数据
  router.post('/fanji', async(req, res) =>{
    let {id}=req.body;//条件
    let updateData=req.body;//更新内容对象
    try {
     await furModel.updateOne({_id:id},updateData);
     res.send({
         code:1,
         msg:'更新数据成功',
       });
    } catch (error) 
    {
     res.send({
         code:0,
         msg:'更新数据失败',
         error, 
     }) 
    }
  })

  //查询分页
  router.get('/', async(req, res) =>{
    let {pageSize=10,page=1}=req.query;
    let result = await furModel.find().limit(pageSize).skip((page-1)*pageSize);
    res.send({
        code:1,
        msg:'查询数据成功',
        data:result,
      });
  })
  //搜索
  router.get('/search', async(req, res) =>{
    let {pageSize=10,page=1,keyword}=req.query;
    // let result=await furModel.find({name:keyword})//精准匹配
    let regExp=new RegExp(keyword,'i');
    let result=await furModel.find({name:regExp})//模糊匹配
    res.send({
        code:1,
        msg:'搜索数据成功',
        data:result,
      });
  })
    //抛出路由对象
module.exports = router;